package org.springblade.modules.system.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import org.springblade.modules.resource.entity.Attach;
import org.springblade.modules.system.config.MesConfig;
import org.springblade.modules.system.domain.BladeFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传工具类
 */
public class QpUploadUtil {
	/**
	 * 去掉多余字符
	 *
	 * @param file
	 * @return
	 */
	private static String trim(String file) {
		if (file == null) {
			return "";
		}
		String t = file.replace("\\", File.separator);
		while (t.indexOf("//") > 0) {
			t = t.replace("//", File.separator);
		}
		return t;
	}

	/**
	 * 删除文件
	 *
	 * @param config
	 * @param targetFile
	 */
	public static void removeFiles(MesConfig config, String uploadType, String targetFile) {
		String tarFileName = config.getUploadPath(uploadType) + File.separator + targetFile;
		File file = new File(trim(tarFileName));
		if (file.exists()) {
			file.delete();
		}
	}


	/**
	 * @param config
	 * @param fileName
	 * @param inFile
	 */
	public static Attach putFile(MesConfig config, String uploadType, String fileName, InputStream inFile) {
		int last = fileName.lastIndexOf(".");
		String ext = "";
		if (last > 0 || last < fileName.length() - 1) {
			ext = fileName.substring(last + 1);
		}
		String tempFile = DateUtil.format(new Date(), "yyyyMM");
		String newName = IdUtil.getSnowflake(1, 2).nextId() + "." + ext;
		String tarFileName = config.getUploadPath(uploadType) + File.separator + tempFile + File.separator + newName;

		File file = new File(trim(tarFileName));
		if (file.exists()) {
			file.delete();
		}
		try {
			FileUtil.writeFromStream(inFile, file);
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
		Long attachID = IdUtil.getSnowflake(1, 2).nextId();
		Attach attach = new Attach();
		attach.setLink("/blade-resource/sys/file/download/" + attachID);
		attach.setDomainUrl(tempFile);
		attach.setIsDeleted(0);
		attach.setOriginalName(fileName);
		attach.setName(newName);
		attach.setId(attachID);
		attach.setAttachSize(file.length());
		attach.setExtension(ext);
		attach.setUploadType(uploadType);
		attach.setStatus(0);
		attach.setCreateTime(new Date());
		attach.setUpdateTime(attach.getCreateTime());
		return attach;

	}

	/**
	 * 取得文件
	 *
	 * @param config
	 */
	public static File downFile(MesConfig config, String uploadType, String name, String path) {
		String tarFileName = config.getUploadPath(uploadType) + File.separator + path + File.separator + name;
		File file = new File(trim(tarFileName));
		return file;
	}


	/**
	 * 转换
	 *
	 * @param attach
	 * @return
	 */
	public static BladeFile convert(Attach attach) {
		if (attach == null) {
			return null;
		}
		BladeFile res = new BladeFile();
		res.setAttachId(attach.getId());
		res.setName(attach.getName());
		res.setOriginalName(attach.getOriginalName());
		res.setLink(attach.getLink());
		res.setDomain(attach.getDomainUrl());
		return res;
	}


	/**
	 * 错误返回结果
	 *
	 * @param response: 响应
	 * @param s：结果
	 * @throws IOException 异常
	 */
	public static void buildResponse(HttpServletResponse response, String s) throws IOException {
		Map<String, String> resMap = new HashMap<>(0);
		resMap.put("code", "405");
		resMap.put("message", s);
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(JSONUtil.toJsonStr(resMap));
		writer.flush();
		writer.close();
	}

}
